const app = getApp()

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

const mybehavior = require("../../../../behaviors/requests")
Page({
  behaviors: [mybehavior],
  data: {
    devices: [],
    connected: false,
    chs: [],
    deviceId: '',
    serviceId: '',
    characteristicId: '',
    fs_upload_url: "https://logisticsengineering.gree.com/container_manage_api/container_manage",
    baseUrl: "https://logisticsengineering.gree.com",
    uploader: [],
    img_src: "",
    base: '',
  },
  getData() {
    let data = {
    }
    let url = this.data.baseUrl + "/pfep2_api/api_user_manage/temp"
    this.post(url, data).then(res => {
      console.log("返回结果", res)
      if (res.code == 20000) {
        this.setData({
          img_data: res.data
        })
        wx.showToast({
          title: res.msg,
          icon: "none"
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: "error"
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },

  print() {
    wx.showLoading({
      title: '处理中...',
    })
    let deviceId = this.data.deviceId
    let serviceId = this.data.serviceId
    let characteristicId = this.data.characteristicId

    // 发送指令到打印机
    var sendData64 = +this.data.base; // 获取要发送的数据数组
    var buffer = new ArrayBuffer(sendData64.length); // 创建一个与数据长度相等的ArrayBuffer
    var view = new DataView(buffer);
    for (var i = 0; i < sendData64.length; i++) {
      view.setUint8(i, sendData64[i]); // 将数据写入ArrayBuffer
    }
    let self = this
    setTimeout(() => {
      wx.hideLoading()
      wx.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        value: buffer,
        success(res) {
          self.setData({
            errMsg: res.errMsg
          })
          console.log('指令发送成功', res);
        },
        fail(err) {
          self.setData({
            errMsg: err.errMsg
          })
          console.log('指令发送失败', err);
        }

      })
    }, 500)

  },
  print2() {
    wx.showLoading({
      title: '处理中...',
    })
    let deviceId = this.data.deviceId
    let serviceId = this.data.serviceId
    let characteristicId = this.data.characteristicId
    var data = this.data.img_data
    var buffer = new ArrayBuffer(data.length); // 创建一个与数据长度相等的ArrayBuffer
    var view = new DataView(buffer);
    for (var i = 0; i < data.length; i++) {
      view.setUint8(i, data[i]); // 将数据写入ArrayBuffer
    }

    let self = this
    setTimeout(() => {
      wx.hideLoading()
      wx.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        value: buffer,
        success(res) {
          console.log('指令发送成功', res);
          self.setData({
            errMsg: res.errMsg
          })
        },
        fail(err) {
          self.setData({
            errMsg: err.errMsg
          })
          console.log('指令发送失败', err);
        }

      })
    }, 500)
  },
  print3() {
    wx.showLoading({
      title: '处理中...',
    })
    let deviceId = this.data.deviceId
    let serviceId = this.data.serviceId
    let characteristicId = this.data.characteristicId
    var data = [0x1b, 0x64, 0x0a];
    var buffer = new ArrayBuffer(data.length); // 创建一个与数据长度相等的ArrayBuffer
    var view = new DataView(buffer);
    for (var i = 0; i < data.length; i++) {
      view.setUint8(i, data[i]); // 将数据写入ArrayBuffer
    }

    let self = this
    setTimeout(() => {
      wx.hideLoading()
      wx.writeBLECharacteristicValue({
        deviceId: deviceId,
        serviceId: serviceId,
        characteristicId: characteristicId,
        value: buffer,
        success(res) {
          console.log('指令发送成功', res);
          self.setData({
            errMsg: res.errMsg
          })
        },
        fail(err) {
          self.setData({
            errMsg: err.errMsg
          })
          console.log('指令发送失败', err);
        }

      })
    }, 500)
  },
  scan() {
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      box_no: "",
      uploader: [],
      img_src: ""
    })

    var _this = this;
    wx.chooseMedia({
      count: 9,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        console.log("图片", res);
        wx.uploadFile({
          url: _this.data.fs_upload_url + '/fs_upload',
          filePath: res.tempFiles[0].tempFilePath,
          name: 'file',
          formData: {
          },
          success(res) {
            const result = JSON.parse(res.data);
            console.log(result)
            if (result.code == 20000) {
              const uploader = _this.data.uploader;

              _this.setData({
                img_src: _this.data.fs_upload_url + '/fs_download?file_id=' + result.data.file_id,
              })

            } else {
              wx.hideLoading();
              wx.showToast({
                title: result.msg,
                icon: "error"
              })
            }

          },
          fail(res) {
            wx.hideLoading()
            wx.showToast({
              title: "未知错误428",
              icon: "error"
            })
          }
        })
        wx.getFileSystemManager().readFile({
          filePath: res.tempFiles[0].tempFilePath, // 图片路径
          encoding: 'base64', // 转换为base64
          success: res => {

            _this.setData({
              base: res.data
            })
            // console.log(_this.data.base); // 转换后的base64
            _this.print()

          },
          fail: err => {
            console.log(err);
          }
        })
      },
      fail: err => {
        wx.hideLoading()

        console.log(err);
      }
    })


  },
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery()
  },
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  },
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    this.setData({
      deviceId: deviceId
    })
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  getBLEDeviceServices(deviceId) {
    let self = this
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {

        self.setData({
          services_arr: res.services.length
        })
        this.getBLEDeviceCharacteristics(deviceId, res.services[1].uuid)
        this.setData({
          serviceId: res.services[1].uuid
        })
        return
        // for (let i = 0; i < res.services.length; i++) {
        //   if (res.services[i].isPrimary) {
        //     this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
        //     this.setData({
        //       serviceId: res.services[i].uuid
        //     })
        //     return
        //   }
        // }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        this.setData({
          characteristicId: res.characteristics[0].uuid,
        })
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            // this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },
  writeBLECharacteristicValue() {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, Math.random() * 255 | 0)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._deviceId,
      characteristicId: this._characteristicId,
      value: buffer,
    })
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },
})
